<?php

declare(strict_types=1);

namespace App\Job;

use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\Playlet;
use App\Model\PlayletEpisodes;
use GuzzleHttp\Client;
use Hyperf\AsyncQueue\Job;
use Psr\Log\LoggerInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Logger\LoggerFactory;
use function PHPUnit\Framework\exactly;

class WxUrlTestJob extends Job
{

    public $playet_id;

    public $applet_id;
    protected LoggerInterface $logger;


    //获取token
    public static $getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";

    public static $getMedialinkUrl = "https://api.weixin.qq.com/wxa/sec/vod/getmedialink";

    public function __construct(int $playet_id)
    {
        $container = ApplicationContext::getContainer();
        $this->logger = $container->get(LoggerFactory::class)->get('log', 'wxRelpace');
        $this->playet_id = $playet_id;
    }

    public function handle()
    {
        try {
            $this->logger->info('开始上传提审剧目');
            $this->logger->info('查询短剧是否存在',[$this->playet_id]);
            //获取短剧ID
            $playletInfo = Playlet::query()->where(['id' => $this->playet_id])->first();

            if(!empty($playletInfo)){

                $this->logger->info('查询小程序是否存在',[10000]);
                $appletData = Applet::query()->where(['id' => 10000])->first();
                if(!empty($appletData)) {
                    $applet_name = $appletData->name;
                    $playlet_name = $playletInfo->name;
                    $this->logger->info('小程序名称',[$applet_name]);
                    $this->logger->info('短剧名称',[$playlet_name]);
                    //获取token
                    $accessToken = $this->getWxAccessToken($appletData->id,$appletData->app_id,$appletData->app_secret);
                    $this->logger->info('微信token',[$accessToken]);
                    if(!empty($accessToken)){
                        //获取这部剧
                        $playletEpisodesData = PlayletEpisodes::query()->select(['id','media_id','old_media_id','media_status'])
                            ->where(['playlet_id' => $playletInfo->id])
                            ->where('media_id','!=',0)->get();
                        if($playletEpisodesData->isNotEmpty()){
                            foreach ($playletEpisodesData as $playletEpisodesDatum){
                                $expire_time = time()+60;
                                $mediaLink  = $this->getMediaInfo($playletEpisodesDatum->media_id,$accessToken,$expire_time);
                                if(!empty($mediaLink)){
                                    $playletEpisodesDatum->wx_original_url = $mediaLink['hls_url'];
                                    $playletEpisodesDatum->wx_original_time = $expire_time;
                                    $playletEpisodesDatum->save();
                                }
                            }
                        }


                    }else{
                        $this->logger->error('小程序:'.$applet_name.' 短剧:'.$playlet_name.' 没有对应的token');
                    }

                }else{
                    $this->logger->error('小程序不存在',[$this->applet_id]);
                }
            }else{
                $this->logger->error('短剧不存在',[$this->playet_id]);
            }
        }catch (\Exception $e){
            $this->logger->error('请求测试微信|错误：' . $e->getLine() . '|' . $e->getMessage());
        }
    }

    public function getWxAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('wx');

        $key = 'wx_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
        return $accessToken;
    }

    public function getMediaInfo($media_id,$accessToken,$expire_time){
        $limit = 100;
        $params         = [
            "media_id"    => $media_id,
            "t"      =>  $expire_time,
        ];
        $linkUrl = self::$getMedialinkUrl.'?access_token='.$accessToken;
        $this->logger->info('请求媒资数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求媒资Url：'.$linkUrl);
        //开始上传
        $result  = $this->request($params, $linkUrl,'POST');
        if($result['errcode'] == 0){
            $this->logger->info('调用媒资接口成功',[$media_id]);
//            $this->logger->info('调用媒资接口成功 返回数据：'.PHP_EOL.var_export(['result' => $result], true));
            return $result['media_info'];

        }else{
            $this->logger->error('调用媒资接口失败 返回数据：'.PHP_EOL.var_export(['result' => $result], true));
        }
        return false;
    }

    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method,$is_multipart = false)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        if ($is_multipart) {
            $headers       =['Content-Type' => 'multipart/form-data'];
        }else{
            $headers       =['Content-Type' => 'application/json;charset=utf-8', 'Accept' => 'application/json','Accept-Charset' => 'utf-8'];
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            if ($is_multipart) {
                $requestParams['multipart'] = $params;
            } else  {
                $requestParams['body'] = json_encode($params,JSON_UNESCAPED_UNICODE);
            }
        }

        $response = $client->request($method,$url, $requestParams);

        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}